#include <qqtlongdatamanager.h>
#include <qqthostaddressmanager.h>

QQtLongDataManager::QQtLongDataManager ( QObject* parent )
    : QObject ( parent )
{
    c0 = new QQtUdpClient ( this );
    p0 = new QQtLongDataProtocol ( this );

    connect ( p0, SIGNAL ( readyRead ( const QQtLongDataSerialization& ) ),
              this, SIGNAL ( readyRead ( const QQtLongDataSerialization& ) ) );

    c0->installProtocol ( p0 );


    QQtHostAddressManager manager;
    QString ip = manager.getHostAddress();
    int port = 4414;
#if USE_HOST_ADDRESS
    c0->bind ( QHostAddress ( ip ), port, QQtUdpClient::DefaultForPlatform );
#else
    c0->bind ( port, QQtUdpClient::DefaultForPlatform );
#endif
    p3line() << c0->localAddress() << c0->localPort();

    c0->setServerAddress ( QHostAddress ( QHostAddress::Broadcast ), 4413 );
}

QQtLongDataManager::~QQtLongDataManager() {}

void QQtLongDataManager::setServerAddress ( QHostAddress address, int port )
{
    c0->setServerAddress ( address, port );
    p3line() << address.toString() << port;
}

void QQtLongDataManager::setServerPort ( int port )
{
    c0->setServerAddress ( QHostAddress ( QHostAddress::Broadcast ), port );
    p3line() << QHostAddress ( QHostAddress::Broadcast ) << port;
}

void QQtLongDataManager::setLocalAddress ( QHostAddress address, int port )
{
    c0->disconnectFromHost();
    c0->bind ( address, port, QQtUdpClient::DefaultForPlatform );

    p3line() << c0->localAddress() << c0->localPort();
}

void QQtLongDataManager::setLocalPort ( int port )
{
    c0->disconnectFromHost();

    QQtHostAddressManager manager;
    QString ip = manager.getHostAddress();
#if USE_HOST_ADDRESS
    c0->bind ( QHostAddress ( ip ), port, QQtUdpClient::DefaultForPlatform );
#else
    c0->bind ( port, QQtUdpClient::DefaultForPlatform );
#endif
    p3line() << c0->localAddress() << c0->localPort();
}

void QQtLongDataManager::setSendBufferSize ( int size )
{
    c0->setSocketOption ( QAbstractSocket::SendBufferSizeSocketOption, size );
}

int QQtLongDataManager::getSendBufferSize()
{
    QVariant var = c0->socketOption ( QAbstractSocket::SendBufferSizeSocketOption );
    return var.toInt();
}

void QQtLongDataManager::setRecvBufferSize ( int size )
{
    c0->setSocketOption ( QAbstractSocket::ReceiveBufferSizeSocketOption, size );
}

int QQtLongDataManager::getRecvBufferSize()
{
    QVariant var = c0->socketOption ( QAbstractSocket::ReceiveBufferSizeSocketOption );
    return var.toInt();
}

QQtUdpClient* QQtLongDataManager::clientHandler()
{
    return c0;
}

QQtLongDataProtocol* QQtLongDataManager::protocolHandler()
{
    return p0;
}

void QQtLongDataManager::sendMessage ( const QQtLongDataSerialization& data )
{
    p0->sendMessage ( data );
}
